#!/bin/bash

# ============================================
# 正确注释掉主配置文件中的默认 server 块
# ============================================

echo "=== 恢复备份 ==="
sudo cp /etc/nginx/nginx.conf.backup /etc/nginx/nginx.conf

echo ""
echo "=== 查看默认 server 块的位置 ==="
grep -n "server {" /etc/nginx/nginx.conf | head -5
grep -n "listen.*80" /etc/nginx/nginx.conf | head -5

echo ""
echo "=== 注释掉主配置文件中的默认 server 块 ==="
# 使用 Python 脚本更精确地注释掉整个 server 块
sudo python3 << 'PYTHON_EOF'
import re

with open('/etc/nginx/nginx.conf', 'r') as f:
    content = f.read()

# 找到包含 default_server 的 server 块并注释掉
lines = content.split('\n')
in_default_server = False
start_line = -1
indent_level = 0

for i, line in enumerate(lines):
    if 'listen.*80' in line and 'default_server' in line:
        in_default_server = True
        start_line = i
        indent_level = len(line) - len(line.lstrip())
    elif in_default_server:
        if line.strip() == '}' and len(line) - len(line.lstrip()) == indent_level:
            # 找到匹配的结束括号
            for j in range(start_line, i + 1):
                if lines[j].strip() and not lines[j].strip().startswith('#'):
                    lines[j] = '#' + lines[j]
            in_default_server = False
            break

# 写回文件
with open('/etc/nginx/nginx.conf', 'w') as f:
    f.write('\n'.join(lines))

print("已注释掉默认 server 块")
PYTHON_EOF

# 或者使用更简单的方法：直接注释掉整个 server 块（第 39-65 行）
# 但需要确保不破坏结构

# 最简单的方法：完全删除主配置文件中的 server 块
sudo cp /etc/nginx/nginx.conf.backup /etc/nginx/nginx.conf

# 找到 server 块的开始和结束行
START_LINE=$(grep -n "listen.*80" /etc/nginx/nginx.conf | grep "default_server" | head -1 | cut -d: -f1)
END_LINE=$(awk -v start="$START_LINE" 'NR > start && /^[[:space:]]*}/ && /^[[:space:]]*$/ {print NR; exit}' /etc/nginx/nginx.conf)

echo "找到 server 块：第 $START_LINE 行到第 $END_LINE 行"

# 注释掉这些行
if [ -n "$START_LINE" ] && [ -n "$END_LINE" ]; then
    sudo sed -i "${START_LINE},${END_LINE}s/^/# /" /etc/nginx/nginx.conf
    echo "已注释掉默认 server 块"
else
    echo "未找到 server 块，尝试手动注释"
    # 手动注释第 39-65 行
    sudo sed -i '39,65s/^/# /' /etc/nginx/nginx.conf
fi

echo ""
echo "=== 验证配置 ==="
sudo nginx -t

echo ""
echo "=== 重启 Nginx ==="
if sudo nginx -t; then
    sudo systemctl restart nginx
    sleep 1
    echo ""
    echo "=== 测试 ==="
    curl -v http://127.0.0.1/api/login/ 2>&1 | head -20
else
    echo "配置验证失败，请检查错误信息"
    echo "查看主配置文件："
    sed -n '35,70p' /etc/nginx/nginx.conf
fi

